package com.imxinxin.zookeeper;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeBean {

    private static volatile Unsafe unsafe = null;


    public static Unsafe get() {
        if (unsafe == null) {
            synchronized (UnsafeBean.class) {
                if (unsafe == null) {
                    unsafe = getUnsafe();
                }
            }
        }
        return unsafe;
    }


    private static Unsafe getUnsafe() {
        Field field = null;
        try {
            field = Unsafe.class.getDeclaredField("theUnsafe");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        assert field != null;
        field.setAccessible(true);
        try {
            return (Unsafe) field.get(null);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return Unsafe.getUnsafe();
    }
}
